package com.digua.base.dialog

import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ViewUtils
import com.digua.base.base.Dialog
import com.digua.base.databinding.DialogLoadingBinding
import com.digua.base.util.StrUtil

class LoadingDialog : Dialog<DialogLoadingBinding>() {

    companion object {
        private val instance: LoadingDialog by lazy { LoadingDialog() }

        fun show(cancelable: Boolean = true, title: String = "加载中..."): LoadingDialog {
            ViewUtils.runOnUiThread {
                instance.isCancelable = cancelable
                if (instance.isShowing()) return@runOnUiThread
                val activity = ActivityUtils.getTopActivity() as AppCompatActivity
                instance.show(activity.supportFragmentManager)
                if (StrUtil.isNotBlank(title)) {
                    ViewUtils.runOnUiThreadDelayed({ instance.ui.loadingTxt.text = title }, 100)
                }
            }
            return instance
        }

        fun dismiss() {
            if (instance.isShowing()) {
                ViewUtils.runOnUiThread { instance.dismiss() }
            }
        }

        fun isShowing() = instance.isShowing()
    }

    override fun initUI() {
        super.initUI()
        dialog?.setCancelable(isCancelable)
        dialog?.setCanceledOnTouchOutside(false)
        val size = SizeUtils.dp2px(200F)
        setWinSize(size, size)
    }

}